package com.baizhi.service.impl;

import com.baizhi.config.redis.AddCacheAnnotation;
import com.baizhi.config.redis.DeleteCacheAnnotation;
import com.baizhi.config.log.LogAnnotation;
import com.baizhi.entity.Banner;
import com.baizhi.entity.R;
import com.baizhi.mapper.BannerMapper;
import com.baizhi.service.BannerService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
public class BannerServiceImpl implements BannerService {
    @Autowired
    private BannerMapper bannerMapper;

    @Transactional
    @LogAnnotation(content = "展示轮播图",type = "select")
    @AddCacheAnnotation
    public Map selectPage(Integer pageNum, Integer pageSize) {
        Map map = new HashMap();
        Page<Banner> page = new Page<>(pageNum, pageSize);
        Page<Banner> bannerPage = bannerMapper.selectPage(page, null);
        List<Banner> banners = bannerPage.getRecords();
        long total = bannerPage.getTotal();
        map.put("code",0);
        map.put("data",banners);
        map.put("count",total);
        return map;
    }
    @DeleteCacheAnnotation
    @Transactional(isolation = Isolation.READ_COMMITTED)
    @LogAnnotation(content = "添加轮播图",type = "insert")
    public void insert(Banner banner) {
        try{
            bannerMapper.insert(banner);
        }catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException();
        }

    }
    @DeleteCacheAnnotation
    @Transactional(isolation = Isolation.READ_COMMITTED)
    @LogAnnotation(content = "删除轮播图",type = "delete")
    public void deleteById(Integer id) {
        try{
            bannerMapper.deleteById(id);
        }catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    @Transactional
    @LogAnnotation(content = "app轮播图查询",type = "select")
    @AddCacheAnnotation
    public R selectBanner(Integer size) {
        log.info(""+size);
        Page<Banner> page = new Page<>(0, size);
        List<Banner> records = null;
        try{
            Page<Banner> bannerPage = bannerMapper.selectPage(page, null);
            records = bannerPage.getRecords();
            return R.ok().put("data",records);
        }catch(Exception e){
            return R.error(1001,"轮播图查询失败");
        }
    }
}
